import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import ValidDatasetName from 'graphql/dataset/validDatasetName.graphql'
import UpdateDataset from 'graphql/dataset/updateDataset.graphql'
import QueryDataset from 'graphql/dataset/queryDataset.graphql'
import deleteDataset from 'graphql/dataset/deleteDataset.graphql'
import { ValidType } from 'components/validForm'
import {
  Form as FormTable,
  Section as TableSection,
  Input,
  Submit,
} from 'components/tableForm'
import { global as globalDuck } from 'ducks'
import { push, replace } from 'connected-react-router'

const getVariables = values => ({
  name: values.name.value,
})

class newDataset extends Component {
  static propTypes = {
    actionSetActiveTab: PropTypes.func.isRequired,
  }

  componentDidMount = () => {
    const { setParentActiveItem } = this.props
    setParentActiveItem('config')
  }

  render() {
    const {
      user, activeDatasetId, link, reLink, activeDataset, orgName,
    } = this.props
    const mailRule = [
      {
        type: ValidType.REGULAR,
        value: /^[\s\S]*.*[^\s][\s\S]*$/,
        errorMessage: '数据集名称不能为空',
      },
      {
        type: ValidType.REGULAR,
        value: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
        errorMessage: '数据集名称由中文、英文数字包括下划线',
      },
      {
        type: ValidType.REMOTE,
        value: {
          query: ValidDatasetName,
          params: { ownerId: user.sub },
        },
        errorMessage: '该名称已经存在于你的账户',
        getResult: re => re.dataset.length === 0,
      },
    ]
    const deleteRule = [
      {
        type: ValidType.EQ,
        value: activeDataset,
        errorMessage: `应输入: ${activeDataset}`,
      },
    ]
    return (
      <FormTable
        initQuery={{
          query: QueryDataset,
          variables: { id: activeDatasetId },
          tableName: 'dataset',
        }}
      >
        <TableSection header="编辑数据集">
          <Input
            name="name"
            header="数据集名称"
            description="存储空间名称由 4 ~ 63 个字符组成 ，可包含 字母、数字、中划线。"
            rules={mailRule}
          />
        </TableSection>
        <Submit
          submit={{
            text: '保存',
            variables: { id: activeDatasetId },
            getVariables,
            mutation: UpdateDataset,
            success: (data) => {
              link('/empty')
              setTimeout(() => {
                if (data && data.update_dataset && data.update_dataset.returning) {
                  const { name } = data.update_dataset.returning[0]
                  console.log(`/dataset/${orgName}/${name}/data`)
                  reLink(`/dataset/${orgName}/${name}/data`)
                }
              })
            },
          }}
          cancle={{ text: '取消', url: `/dataset/${orgName}/${activeDataset}/data` }}
          validFields={['name']}
          redirect
        />
        <TableSection header="危险操作区" red>
          <Input
            name="deleteName"
            header="删除数据集"
            description={`为了安全起见请您输入当前要删除的数据集名称：${activeDataset}`}
            rules={deleteRule}
            red
          />
        </TableSection>
        <Submit
          submit={{
            text: '删除',
            variables: { id: activeDatasetId },
            getVariables: () => {},
            mutation: deleteDataset,
            success: () => {
              link('/empty')
              setTimeout(() => {
                reLink(`/org/${orgName}/dataset`)
              })
            },
          }}
          validFields={['deleteName']}
          red
        />
      </FormTable>
    )
  }
}

const mapStateToProps = state => ({
  user: globalDuck.selectors.user(state),
})

const mapDispatchToProps = {
  link: push,
  reLink: replace,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(newDataset)
